//
//  LZNewLoginViewController.m
//  laziz_Merchant
//
//  Created by xbnzd on 17/3/15.
//  Copyright © 2017年 XBN. All rights reserved.
//



#import "LZNewLoginViewController.h"
#import "UIViewController+NavigationItemSetting.h"
#import "LZNewRegisterViewController.h"
#import "LZRecoveryPasswordViewController.h"
#import "LZMyChangeInfoViewController.h"
#import "GVUserDefaults+LZProperties.h"
#import "LZAreaCodeViewController.h"
#import "LZNotificationPresenter.h"
#import "UIView+Rotation.h"
#import "LZUserInfoPresenter.h"
#import "LZCurrentUserInfo.h"
#import "LZPopAlertView.h"
#import "LZActionSheet.h"
#import "LZRemindView.h"
#import "AppDelegate.h"
#import "MJExtension.h"
#import "LZUserModel.h"
#import "LZAlertView.h"
#import "extobjc.h"

//#import "LZNewPromotionVC.h"

@interface LZNewLoginViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;
@property (weak, nonatomic) IBOutlet UIButton *registerBtn;
@property (weak, nonatomic) IBOutlet UIButton *moreLoginModeBtn;
@property (weak, nonatomic) IBOutlet UILabel *phoneAreaCodeLabel;
@property (weak, nonatomic) IBOutlet UIImageView *areaCodeImage;
@property (weak, nonatomic) IBOutlet UITextField *userNameTextField;
@property (weak, nonatomic) IBOutlet UIButton *getVerificationCodeBtn;
@property (weak, nonatomic) IBOutlet UILabel *timeDownLabel;
@property (weak, nonatomic) IBOutlet UITextField *passWordTextField;
@property (weak, nonatomic) IBOutlet UIButton *forgetPasswordBtn;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *logoImgTopToSupeViewCST;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *userNameTextFieldTopToTextCST;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *loginBtnTopToPasswordTFCST;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *registerBtnWidth;

@property (strong, nonatomic) UINavigationController *navVC;
@property (strong, nonatomic) LZAreaCodeViewController *areaCodeVC;
@property (nonatomic, strong) LZUserInfoPresenter * userInfoPresenter;
@property (assign, nonatomic) LoginType loginType; //登陆类型 默认快捷登陆
@property (weak, nonatomic) LZActionSheet  * actionSheet;
@property (nonatomic, strong) NSTimer * timer;          //验证码倒计时
@property (nonatomic, assign) int count;
@property (nonatomic, strong) LZPopAlertView *passwordRecoveryPopView;
@end

@implementation LZNewLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self configureUI];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
}

- (BOOL)fd_prefersNavigationBarHidden {
    return YES;
}

- (void)dealloc {
    
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
}


#pragma mark - private method 根据登陆类型配置显示页面 三种登陆方法
- (void)showLoginViewForLoginType
{
    self.userNameTextField.text = nil;
    self.passWordTextField.text = nil;
    if (self.loginType == kLogin_fast) {
        self.areaCodeImage.hidden = NO;
        self.phoneAreaCodeLabel.hidden = NO;
        self.getVerificationCodeBtn.hidden = NO;
        self.timeDownLabel.hidden = YES;
        self.forgetPasswordBtn.hidden = YES;
        self.userNameTextField.placeholder = LZLocalizedString(@"mobile_phone", nil);
        self.passWordTextField.placeholder = LZLocalizedString(@"change_verificode", nil);
        self.passWordTextField.secureTextEntry = NO;
        self.userNameTextField.keyboardType = UIKeyboardTypeNumberPad;
        self.passWordTextField.keyboardType = UIKeyboardTypeNumberPad;
        
    }else if (self.loginType == kLogin_phone){
        
        self.areaCodeImage.hidden = NO;
        self.phoneAreaCodeLabel.hidden = NO;
        self.getVerificationCodeBtn.hidden = YES;
        self.timeDownLabel.hidden = YES;
        self.forgetPasswordBtn.hidden = NO;
        self.userNameTextField.placeholder = LZLocalizedString(@"mobile_phone", nil);
        self.passWordTextField.placeholder = LZLocalizedString(@"password", nil);
        self.passWordTextField.secureTextEntry = YES;
        self.userNameTextField.keyboardType = UIKeyboardTypeNumberPad;
        self.passWordTextField.keyboardType = UIKeyboardTypeDefault;
        
        [self showPasswordRecoveryPopView];

    }else if (self.loginType == kLogin_eMail){
        self.areaCodeImage.hidden = YES;
        self.phoneAreaCodeLabel.hidden = YES;
        self.getVerificationCodeBtn.hidden = YES;
        self.timeDownLabel.hidden = YES;
        self.forgetPasswordBtn.hidden = NO;
        self.userNameTextField.placeholder = LZLocalizedString(@"login_email_or_account", nil);
        self.passWordTextField.placeholder = LZLocalizedString(@"password", nil);
        self.passWordTextField.secureTextEntry = YES;
        self.userNameTextField.keyboardType = UIKeyboardTypeDefault;
        self.passWordTextField.keyboardType = UIKeyboardTypeDefault;
        
        [self showPasswordRecoveryPopView];
    }
    
}


/**
 邮箱和密码登陆
 */
- (void)tryLoginForEmailAndPassword
{
    //=================================================
    //这里做两层判断,因为邮箱和用户名密码登陆无法区分.后台接口即使合并,扔无法区分.如果只是本地做正则判断是否是邮箱,太过于片面, 所以,做两次提交,先提交邮箱,如果失败再提交 用户名和密码登陆.
    //=========================================
    
    if (self.userNameTextField.text.length <= 0) {
        [LZRemindView initWithImage:[UIImage imageNamed:@"错误提示"] andContent:LZLocalizedString(@"login_please_enter_email_or_account", nil)];
        return;
    }
    
    if (self.passWordTextField.text.length <= 0) {
        [LZRemindView initWithImage:[UIImage imageNamed:@"错误提示"] andContent:LZLocalizedString(@"enter_password", @"")];
        return;
    }

    NSString * userName = [NSString stringWithFormat:@"%@", self.userNameTextField.text];
    NSString * passwordStr = [NSString stringWithFormat:@"%@", self.passWordTextField.text];
    
    DLog(@"邮箱或者账户登录：/r userName:%@ /r passwordStr:%@", userName, passwordStr);
    [self startLoadingViewForView:self.view loadingViewUserInteractionEnabled:YES];
    
    @weakify(self);
    [self.userInfoPresenter emailLoginWithEmail:userName Password:passwordStr Success:^(id data) {
        DLog(@"邮箱或者账户登录成功：\r%@", data);
        @strongify(self);
        [self stopLoadingViewForView:self.view];
        
        //登录类型
        NSDictionary *dataDic = (NSDictionary *)data;
        LZCurrentUserInfo *userInfo = [LZCurrentUserInfo mj_objectWithKeyValues:dataDic[@"data"]];
        if (userInfo) {
            [LZUserModel Instance].userInfo = userInfo;
            [GVUserDefaults standardUserDefaults].userId = userInfo.userId;
            [GVUserDefaults standardUserDefaults].loginType = kLogin_eMail;
            [GVUserDefaults standardUserDefaults].userToken = userInfo.token;
            [GVUserDefaults standardUserDefaults].userId = userInfo.userId;
            [LZNotificationPresenter setNotificationAlias:userInfo.userId];
            [GVUserDefaults standardUserDefaults].isSetPassword = YES;
            [GVUserDefaults standardUserDefaults].userType = userInfo.userType;
            [GVUserDefaults standardUserDefaults].email = userInfo.email;
            [GVUserDefaults standardUserDefaults].cellphone = userInfo.cellphone;
            
            //商户状态 0 商户未认证 1 待审核 2 正常 3 审核退回 4 已停用
            [GVUserDefaults standardUserDefaults].authType = userInfo.merchantState;
            if (userInfo.merchantState != kAuthType_noneAuth) {
                [GVUserDefaults standardUserDefaults].sellerId = userInfo.sellerId;
            }
            
            if ([userInfo.userType integerValue] == kUserType_staff) {
                [GVUserDefaults standardUserDefaults].staffRole = userInfo.role;
            }
            
        }
        
        //登陆成功，切换
        AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
        [appDelegate setRootForHomeVCWithIsShowLeadingView:NO];
        
    } Failure:^(NSString *fail) {
        DLog(@"邮箱账户登陆失败：\r%@", fail);
        
        //邮箱登陆失败,尝试用户密码登陆
        @strongify(self);
        
        [self stopLoadingViewForView:self.view];
        [self tryLoginForUserNameAndPassword];
//        [self stopLoadingViewForView:self.view];
//        
//        if ([fail isEqualToString:@"0400034"]) {
//            LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"mag_account_stopstate", nil)
//                                                             andImage:nil
//                                                    cancelButtonTitle:LZLocalizedString(@"cancel", nil)
//                                                    otherButtonTitles:nil, nil];
//            [alert show];
//        }
//        else {
//            [LZRemindView initWithImage:[UIImage imageNamed:@"错误提示"] andContent:LZLocalizedString(@"account_failed", @"")];
//        }

    }];

}


/**
 尝试用户名和密码登陆
 */
- (void)tryLoginForUserNameAndPassword
{
    NSString * userName = [NSString stringWithFormat:@"%@",self.userNameTextField.text];
    NSString * passwordStr = [NSString stringWithFormat:@"%@", self.passWordTextField.text];
    
    DLog(@"用户名密码登录：/r userName:%@ /r passwordStr:%@", userName, passwordStr);
    
    [self startLoadingViewForView:self.view loadingViewUserInteractionEnabled:YES];
    
    @weakify(self);
    [self.userInfoPresenter userLoginCellPhone:userName andPasswordOrVerifiCode:passwordStr andLoginType:2 andonSuccess:^(id data) {
        DLog(@"用户名密码登录：\r%@", data);
        @strongify(self);
        [self stopLoadingViewForView:self.view];
        
        //登录类型
        NSDictionary *dataDic = (NSDictionary *)data;
        LZCurrentUserInfo *userInfo = [LZCurrentUserInfo mj_objectWithKeyValues:dataDic[@"data"]];
        if (userInfo) {
            [LZUserModel Instance].userInfo = userInfo;
            [GVUserDefaults standardUserDefaults].userId = userInfo.userId;
            [GVUserDefaults standardUserDefaults].loginType = kLogin_eMail;
            [GVUserDefaults standardUserDefaults].userToken = userInfo.token;
            [GVUserDefaults standardUserDefaults].userId = userInfo.userId;
            [LZNotificationPresenter setNotificationAlias:userInfo.userId];
            [GVUserDefaults standardUserDefaults].isSetPassword = YES;
            [GVUserDefaults standardUserDefaults].userType = userInfo.userType;
            [GVUserDefaults standardUserDefaults].email = userInfo.email;
            [GVUserDefaults standardUserDefaults].cellphone = userInfo.cellphone;
            
            //商户状态 0 商户未认证 1 待审核 2 正常 3 审核退回 4 已停用
            [GVUserDefaults standardUserDefaults].authType = userInfo.merchantState;
            if (userInfo.merchantState != kAuthType_noneAuth) {
                [GVUserDefaults standardUserDefaults].sellerId = userInfo.sellerId;
            }
            
            if ([userInfo.userType integerValue] == kUserType_staff) {
                [GVUserDefaults standardUserDefaults].staffRole = userInfo.role;
            }
            
        }
        
        //登陆成功，切换
        AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
        [appDelegate setRootForHomeVCWithIsShowLeadingView:NO];
        
    } onFail:^(NSString *fail) {
        
        DLog(@"用户名密码登录：\r%@", fail);
        @strongify(self);
        [self stopLoadingViewForView:self.view];
        
        if ([fail isEqualToString:@"0400034"]) {
            LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"mag_account_stopstate", nil)
                                                             andImage:nil
                                                    cancelButtonTitle:LZLocalizedString(@"cancel", nil)
                                                    otherButtonTitles:nil, nil];
            [alert show];
        }
        else {
            [LZRemindView initWithImage:[UIImage imageNamed:@"错误提示"] andContent:LZLocalizedString(@"failed_to_login", @"")];
        }
    }];

}

/**
 手机号和密码登陆
 */
- (void)loginForPhoneAndPassword
{
    if (self.userNameTextField.text.length <= 0) {
        [LZRemindView initWithImage:[UIImage imageNamed:@"错误提示"] andContent:LZLocalizedString(@"login_enter_mobile", nil)];
        return;
    }
    
    if (self.passWordTextField.text.length <= 0) {
        [LZRemindView initWithImage:[UIImage imageNamed:@"错误提示"] andContent:LZLocalizedString(@"enter_password", @"")];
        return;
    }
    
    NSString * userName = [NSString stringWithFormat:@"%@%@", self.phoneAreaCodeLabel.text, self.userNameTextField.text];
    NSString * passwordStr = [NSString stringWithFormat:@"%@", self.passWordTextField.text];
    
    DLog(@"手机账户登录：/r userName:%@ /r passwordStr:%@", userName, passwordStr);
    
    [self startLoadingViewForView:self.view loadingViewUserInteractionEnabled:YES];
    
    @weakify(self);
    [self.userInfoPresenter userLoginCellPhone:userName andPasswordOrVerifiCode:passwordStr andLoginType:self.loginType andonSuccess:^(id data) {
        DLog(@"手机账户登录成功：\r%@", data);
        @strongify(self);
        [self stopLoadingViewForView:self.view];
        
        //登录类型
        NSDictionary *dataDic = (NSDictionary *)data;
        LZCurrentUserInfo *userInfo = [LZCurrentUserInfo mj_objectWithKeyValues:dataDic[@"data"]];
        if (userInfo) {
            [LZUserModel Instance].userInfo = userInfo;
            [GVUserDefaults standardUserDefaults].phoneAreaCode = self.phoneAreaCodeLabel.text;
            [GVUserDefaults standardUserDefaults].userId = userInfo.userId;
            [GVUserDefaults standardUserDefaults].loginType = kLogin_phone;
            [GVUserDefaults standardUserDefaults].userToken = userInfo.token;
            [GVUserDefaults standardUserDefaults].userId = userInfo.userId;
            [LZNotificationPresenter setNotificationAlias:userInfo.userId];
            [GVUserDefaults standardUserDefaults].isSetPassword = YES;
            [GVUserDefaults standardUserDefaults].userType = userInfo.userType;
            [GVUserDefaults standardUserDefaults].staffRole = @"-1";
            [GVUserDefaults standardUserDefaults].email = userInfo.email;
            [GVUserDefaults standardUserDefaults].cellphone = userInfo.cellphone;
            
            //商户状态 0 商户未认证 1 待审核 2 正常 3 审核退回 4 已停用
            [GVUserDefaults standardUserDefaults].authType = userInfo.merchantState;
            if (userInfo.merchantState != kAuthType_noneAuth) {
                [GVUserDefaults standardUserDefaults].sellerId = userInfo.sellerId;
            }
            
        }
        
        //登陆成功，切换
        AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
        [appDelegate setRootForHomeVCWithIsShowLeadingView:NO];
        
    } onFail:^(NSString *fail) {
        
        DLog(@"手机账户登陆失败：\r%@", fail);
        @strongify(self);
        [self stopLoadingViewForView:self.view];
        
        if ([fail isEqualToString:@"0400034"]) {
            LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"mag_account_stopstate", nil)
                                                             andImage:nil
                                                    cancelButtonTitle:LZLocalizedString(@"cancel", nil)
                                                    otherButtonTitles:nil, nil];
            [alert show];
        }
        else {
            [LZRemindView initWithImage:[UIImage imageNamed:@"错误提示"] andContent:LZLocalizedString(@"account_failed", @"")];
        }
    }];

}

/**
 快捷登录
 */
- (void)quickTypeLogin
{
    if (self.userNameTextField.text.length <= 0) {
        [LZRemindView initWithImage:[UIImage imageNamed:@"错误提示"] andContent:LZLocalizedString(@"login_enter_mobile", @"")];
        return;
    }
    
    NSString * userName = [NSString stringWithFormat:@"%@%@", self.phoneAreaCodeLabel.text, self.userNameTextField.text];
    NSString * passwordStr = [NSString stringWithFormat:@"%@", self.passWordTextField.text];
    
    if (passwordStr.length <= 0) {
        [LZRemindView initWithImage:[UIImage imageNamed:@"错误提示"] andContent:LZLocalizedString(@"login_enter_verifi_code", @"")];
        return;
    }
    
    DLog(@"快捷登录：/r userName:%@ /r passwordStr=%@ /r", userName, passwordStr);
    
    @weakify(self);
    [self startLoadingViewForView:self.view loadingViewUserInteractionEnabled:YES];
    [self.userInfoPresenter userLoginCellPhone:userName andPasswordOrVerifiCode:passwordStr andLoginType:self.loginType andonSuccess:^(id data) {
        @strongify(self);
        DLog(@"快捷登录成功：\r%@", data);
        [self stopLoadingViewForView:self.view];
        //登录类型
        NSDictionary *dataDic = (NSDictionary *)data;
        LZCurrentUserInfo *userInfo = [LZCurrentUserInfo mj_objectWithKeyValues:dataDic[@"data"]];
        if (userInfo) {
            [LZUserModel Instance].userInfo = userInfo;
            [GVUserDefaults standardUserDefaults].phoneAreaCode = self.phoneAreaCodeLabel.text;
            [GVUserDefaults standardUserDefaults].userId = userInfo.userId;
            [GVUserDefaults standardUserDefaults].loginType = kLogin_fast;
            [GVUserDefaults standardUserDefaults].userToken = userInfo.token;
            [GVUserDefaults standardUserDefaults].userId = userInfo.userId;
            [LZNotificationPresenter setNotificationAlias:userInfo.userId];
            [GVUserDefaults standardUserDefaults].isSetPassword = userInfo.hasPassword;
            [GVUserDefaults standardUserDefaults].email = userInfo.email;
            [GVUserDefaults standardUserDefaults].cellphone = userInfo.cellphone;
            
            //商户状态 0 商户未认证 1 待审核 2 正常 3 审核退回 4 已停用
            [GVUserDefaults standardUserDefaults].authType = userInfo.merchantState;
            if (userInfo.merchantState != kAuthType_noneAuth) {
                [GVUserDefaults standardUserDefaults].sellerId = userInfo.sellerId;
            }
        }
        
        AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
        if ([GVUserDefaults standardUserDefaults].isSetPassword == YES) {
            //登陆成功，切换
            [appDelegate setRootForHomeVCWithIsShowLeadingView:NO];
        }
        else {
            [appDelegate setRootForHomeVCWithIsShowLeadingView:NO];
            LZMyChangeInfoViewController * vc = [[LZMyChangeInfoViewController alloc] init];
            vc.type = LZ_MYCHANGEINFO_TYPE_SETPASSWORD;
            [appDelegate.rootNavigationController pushViewController:vc animated:NO];
        }
        
    } onFail:^(NSString *fail) {
        
        @strongify(self);
        DLog(@"快捷登录失败：\r%@", fail);
        
        [self stopLoadingViewForView:self.view];
        
        if ([fail isEqualToString:@"0400001"] || [fail isEqualToString:@"0100010"] || [fail isEqualToString:@"0500001"]) {
            [LZRemindView initWithImage:[UIImage imageNamed:@"错误提示"] andContent:LZLocalizedString(@"enter_invalid_verifi", @"")]; //0400001 验证码错误
        }
        else if ([fail isEqualToString:@"0400034"]) {
            LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"mag_account_stopstate", nil)
                                                             andImage:nil
                                                    cancelButtonTitle:LZLocalizedString(@"cancel", nil)
                                                    otherButtonTitles:nil, nil];
            [alert show];
        }
        else {
            [LZRemindView initWithImage:[UIImage imageNamed:@"错误提示"] andContent:LZLocalizedString(@"login_failed", @"")]; //0400002 登陆失败
        }
        
    }];
}


/**
 打开区号选择器
 */
- (void)openAreaCodeVC
{
    [self presentViewController:self.navVC animated:YES completion:^{
        
    }];
    @weakify(self);
    self.areaCodeVC.SelectedAreaCodeBlock = ^(NSString *codeStr){
        @strongify(self);
        self.phoneAreaCodeLabel.text = codeStr;
    };
}

#pragma mark - 密码寻找提示pop. 只提醒一次
- (void)showPasswordRecoveryPopView
{
    BOOL firstIn = ![[[NSUserDefaults standardUserDefaults] objectForKey:@"password_recovery"] boolValue];
    if (firstIn) {
        [self.view addSubview:self.passwordRecoveryPopView];
        [self.passwordRecoveryPopView loadText:LZLocalizedString(@"password_recovery", nil) anchor:CGPointMake(self.forgetPasswordBtn.frame.origin.x + self.forgetPasswordBtn.frame.size.width/2, self.forgetPasswordBtn.frame.origin.y)];
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"password_recovery"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    
}

- (void)hiddenPasswordRecoveryPopView
{
    if (_passwordRecoveryPopView) {
        self.passwordRecoveryPopView.hidden = YES;
        [self.passwordRecoveryPopView removeFromSuperview];
        _passwordRecoveryPopView = nil;
    }
}


#pragma mark - 倒计时 开启 关闭倒计时
- (void)startTimer {
    
    self.timeDownLabel.text = @"60s";
    [self.timer invalidate];
    self.count = 0;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1
                                                  target:self
                                                selector:@selector(updateTime)
                                                userInfo:nil
                                                 repeats:YES];
    
    self.timeDownLabel.hidden = NO;
    self.getVerificationCodeBtn.hidden = YES;
}

- (void)stopTimer {
    [self.timer invalidate];
    self.timeDownLabel.hidden = YES;
    self.getVerificationCodeBtn.hidden = NO;
}

- (void)updateTime
{
    self.count ++;
    if (self.count >= 60)
    {
        [self stopTimer];
        return;
    }
    
    self.timeDownLabel.text = [NSString stringWithFormat:@"%is", 60-self.count];
    
    if (self.count == 60) {
        self.timeDownLabel.hidden = YES;
        self.getVerificationCodeBtn.hidden = NO;
    }
}

#pragma mark - private button action 登陆按钮, 去往注册, 切换登陆方式,获取验证码,忘记密码

/**
 登录方法

 @param sender <#sender description#>
 */
- (IBAction)loginBtnAction:(id)sender {
//    LZNewPromotionVC *vc = [[LZNewPromotionVC alloc]initWithNibName:@"LZNewPromotionVC" bundle:nil];
//    [self.navigationController pushViewController:vc animated:YES];
//    return;
    
    if (self.loginType == kLogin_fast) {
        
        [self quickTypeLogin];
        
    }else if (self.loginType == kLogin_phone){
        
        [self loginForPhoneAndPassword];
        
    }else if (self.loginType == kLogin_eMail){
        
        [self tryLoginForEmailAndPassword];
    }
}


/**
 去往注册界面

 @param sender <#sender description#>
 */
- (IBAction)registerBtnAction:(id)sender {
    
    [self hiddenPasswordRecoveryPopView];
    
    LZNewRegisterViewController *vc = [[LZNewRegisterViewController alloc] initWithNibName:@"LZNewRegisterViewController" bundle:nil];
    [self.navigationController pushViewController:vc animated:YES];
}

/**
 切换登陆方式

 @param sender <#sender description#>
 */
- (IBAction)moreLoginModeBtnAction:(id)sender {
    
    [self hiddenPasswordRecoveryPopView];
    
    if (self.loginType == kLogin_fast) {
        
        [self.actionSheet ReloadTableViewArrayTitle:@[@[LZLocalizedString(@"login_mobile_phone_and_password", nil), LZLocalizedString(@"login_email_and_password", nil)], @[LZLocalizedString(@"cancel", nil)]]];
        [self.actionSheet ShowView];
        
    }else if (self.loginType == kLogin_phone){
        
        [self.actionSheet ReloadTableViewArrayTitle:@[@[LZLocalizedString(@"login_quick_login", nil), LZLocalizedString(@"login_email_and_password", nil)], @[LZLocalizedString(@"cancel", nil)]]];
        [self.actionSheet ShowView];
    
    }else{
        
        [self.actionSheet ReloadTableViewArrayTitle:@[@[LZLocalizedString(@"login_quick_login", nil), LZLocalizedString(@"login_mobile_phone_and_password", nil)], @[LZLocalizedString(@"cancel", nil)]]];
        [self.actionSheet ShowView];
    
    }
}


/**
 快捷登陆获取验证码

 @param sender <#sender description#>
 */
- (IBAction)getVerificationCodeAction:(id)sender {
    
    if (self.userNameTextField.text.length <= 0) {
        [LZRemindView initWithImage:[UIImage imageNamed:@"错误提示"] andContent:LZLocalizedString(@"login_enter_mobile", @"")];
        return;
    }
    //验证码类型（1注册，2快捷登录，3身份验证，4绑定手机）
    NSString * mobileStr = [NSString stringWithFormat:@"%@%@",self.phoneAreaCodeLabel.text,self.userNameTextField.text];
    
    [self startLoadingViewForView:self.view loadingViewUserInteractionEnabled:YES];
    
    @weakify(self);
    [self.userInfoPresenter userGetVerificationPhoneNum:mobileStr andonSuccess:^(id data) {
        @strongify(self);
        DLog(@"获取验证码：\r%@", data);
        //显示倒计时
        [self startTimer];
        
        [self stopLoadingViewForView:self.view];
#if DEBUG
        self.passWordTextField.text = [NSString stringWithFormat:@"%@", [data objectForKey:@"data"]];
#endif

    } onFail:^(NSString *fail) {
        @strongify(self);
        DLog(@"获取验证码失败：\r%@", fail);
        [self stopLoadingViewForView:self.view];
        self.getVerificationCodeBtn.highlighted = YES;
        if ([fail isEqualToString:@"9999999"]) {
//            [LZRemindView initWithImage:[UIImage imageNamed:@"错误提示"]
//                             andContent:LZLocalizedString(@"send_code_maxnum_remind", nil)];
            LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"send_code_maxnum_remind", nil)
                                                             andImage:[UIImage imageNamed:@"错误提示"]
                                                    cancelButtonTitle:LZLocalizedString(@"confirm", nil)
                                                    otherButtonTitles:nil, nil];
            [alert show];
            
        }
        else {
            
            [LZRemindView initWithImage:[UIImage imageNamed:@"错误提示"]
                             andContent:LZLocalizedString(@"vificode_failed", nil)];
            
        }
    } ];

}

- (IBAction)forgetPasswordBtnAction:(id)sender {
    
    [self hiddenPasswordRecoveryPopView];
    
    LZRecoveryPasswordViewController *vc = [[LZRecoveryPasswordViewController alloc] initWithNibName:@"LZRecoveryPasswordViewController" bundle:nil];
    if (self.loginType == kLogin_phone) {
        vc.isRecoveryPasswordByPhone = YES;
    }else{
        vc.isRecoveryPasswordByPhone = NO;
    }
    
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - textfield delegate
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self hiddenPasswordRecoveryPopView];
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (self.loginType == kLogin_fast) {
        
        NSInteger totalLength = textField.text.length;
        NSInteger replaceLength = string.length;
        NSInteger changeLength = range.length;
        if (totalLength + replaceLength - changeLength > 1) {
            self.getVerificationCodeBtn.highlighted = YES;
            self.getVerificationCodeBtn.userInteractionEnabled = YES;
        }else{
            self.getVerificationCodeBtn.highlighted = NO;
            self.getVerificationCodeBtn.userInteractionEnabled = NO;
        }
    }
    
    return YES;
}

#pragma mark - Configure UI
- (void)configureUI
{
    self.umLogPageViewName = @"登陆页面";
    _userInfoPresenter = [[LZUserInfoPresenter alloc] init];
    self.titleLabel.text = LZLocalizedString(@"login_loginnow", nil);
    [self.loginBtn setTitle:LZLocalizedString(@"login_login", nil) forState:UIControlStateNormal];
    [self.registerBtn setTitle:LZLocalizedString(@"login_register", nil) forState:UIControlStateNormal];
    [self.moreLoginModeBtn setTitle:LZLocalizedString(@"login_change_login_mode", nil) forState:UIControlStateNormal];
    
    // 判断是否切换了语言并弹提示框刷新UI
    [[LZLanguageManager shareInstance] showChangeLanguageAlert];
    
    self.view.backgroundColor = UIColorFromRGB(0x333333, 1);
    
    [self lz_setCustomBarAlpha:0];
    
    [self.areaCodeImage setLanguageRotaion];
    
    if ([GVUserDefaults standardUserDefaults].loginType < 1) {
        self.loginType = kLogin_fast;
    }else{
        self.loginType = [GVUserDefaults standardUserDefaults].loginType;
        if (self.loginType == kLogin_fast) {
            self.loginType = kLogin_phone;
        }
    }
    
    if ([GVUserDefaults standardUserDefaults].phoneAreaCode.length > 0) {
        self.phoneAreaCodeLabel.text = [GVUserDefaults standardUserDefaults].phoneAreaCode;
    }else{
        self.phoneAreaCodeLabel.text = @"+973";
    }
    
    [self showLoginViewForLoginType];
    
    self.getVerificationCodeBtn.userInteractionEnabled = NO;
    
    self.timeDownLabel.layer.cornerRadius = 3.;
    self.timeDownLabel.layer.masksToBounds = YES;
    self.timeDownLabel.layer.borderColor = UIColorFromRGB(0xcccccc, 1).CGColor;
    self.timeDownLabel.layer.borderWidth = 1;
    
    GET_SCREEN_SCALE(scale);
    self.phoneAreaCodeLabel.font = [UIFont systemFontOfSize:17*scale];
    
    self.userNameTextField.delegate = self;
    self.userNameTextField.font = [UIFont systemFontOfSize:17*scale];
    [self.userNameTextField setTintColor:UIColorFromRGB(0x33a928, 1)];
    [self.userNameTextField setValue:UIColorFromRGB(0x999999, 1) forKeyPath:@"_placeholderLabel.textColor"];
    
    self.passWordTextField.font = [UIFont systemFontOfSize:17*scale];
    if (self.loginType == kLogin_fast) {
        self.passWordTextField.secureTextEntry  = NO;
        self.passWordTextField.keyboardType = UIKeyboardTypeNumberPad;
    }else{
        self.passWordTextField.secureTextEntry  = YES;
        self.passWordTextField.keyboardType = UIKeyboardTypeDefault;
    }
    
    [self.passWordTextField setTintColor:UIColorFromRGB(0x33a928, 1)];
    [self.passWordTextField setValue:UIColorFromRGB(0x999999, 1) forKeyPath:@"_placeholderLabel.textColor"];
    
    self.loginBtn.backgroundColor = UIColorFromRGB(0x33a928, 1);
    self.loginBtn.layer.cornerRadius = 22.;
    self.loginBtn.layer.masksToBounds = YES;
    
    self.registerBtn.layer.cornerRadius = 22.;
    self.registerBtn.layer.borderColor = UIColorFromRGB(0x33a928, 1).CGColor;
    self.registerBtn.layer.borderWidth = 1;
    
    self.registerBtnWidth.constant = 315*scale;
    self.logoImgTopToSupeViewCST.constant = 79 *scale;
    self.userNameTextFieldTopToTextCST.constant = 90 *scale;
    self.loginBtnTopToPasswordTFCST.constant = 90 *scale;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(openAreaCodeVC)];
    self.phoneAreaCodeLabel.userInteractionEnabled = YES;
    [self.phoneAreaCodeLabel addGestureRecognizer:tap];
}


#pragma mark - 控件初始化
- (LZActionSheet *)actionSheet {
    if (_actionSheet == nil) {
        LZActionSheet *sheet = [[LZActionSheet alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        _actionSheet = sheet;
        [_actionSheet creatHeaderWithTitle:@"" andHeight:0];
        [[UIApplication sharedApplication].keyWindow addSubview:_actionSheet];
        
        @weakify(self);
        _actionSheet.ClickSheetBlock = ^(NSIndexPath *indexPath, id obj) {
            if (indexPath.section == 0) {
                @strongify(self);
                if (self.loginType == kLogin_fast) {
                    if (indexPath.row == 0) {//
                        self.loginType = kLogin_phone;
                    }else{
                        self.loginType = kLogin_eMail;
                    }
                }else if (self.loginType == kLogin_phone){
                    if (indexPath.row == 0) {//
                        self.loginType = kLogin_fast;
                    }else{
                        self.loginType = kLogin_eMail;
                    }
                }else if (self.loginType == kLogin_eMail){
                    if (indexPath.row == 0) {//
                        self.loginType = kLogin_fast;
                    }else{
                        self.loginType = kLogin_phone;
                    }
                }
                
                [self showLoginViewForLoginType];
            }
           
        };
    }
    
    return _actionSheet;
}

- (UINavigationController *)navVC
{
    if (!_navVC) {
        _navVC = [[UINavigationController alloc] initWithRootViewController:self.areaCodeVC];
        _navVC.navigationBar.translucent = NO;
        _navVC.navigationBar.barTintColor = [UIColor blackColor];
        _navVC.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:[UIFont systemFontOfSize:18]};
    }
    
    return _navVC;
}

- (LZAreaCodeViewController *)areaCodeVC
{
    if (!_areaCodeVC) {
        _areaCodeVC = [[LZAreaCodeViewController alloc] initWithNibName:@"LZAreaCodeViewController" bundle:nil];
    }
    
    return _areaCodeVC;
}

- (LZPopAlertView *)passwordRecoveryPopView
{
    if (_passwordRecoveryPopView) {
        return _passwordRecoveryPopView;
    }
    
    _passwordRecoveryPopView = [[NSBundle mainBundle] loadNibNamed:@"LZPopAlertView" owner:self options:nil].lastObject;
    
    return _passwordRecoveryPopView;
}


@end
